/* ====================================================================
 * (#)Header: InterceptorUtils.java
 * (#)Revision: 
 * (#)Date Created: 2009-06-03
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.service.ejb.interceptor;

import java.util.Arrays;
import java.util.Collection;

import javax.interceptor.InvocationContext;

/**
 * 
 * <code>InterceptorUtils</code> is ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
/**
 * <code>InterceptorUtils</code> is ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class InterceptorUtils {
	
	public static String getMessageBeforeInvokation(InvocationContext inv) {
		StringBuilder stringBuilder = new StringBuilder();
		Object[] params = inv.getParameters();
		stringBuilder.append(getMethodFullName(inv));
		stringBuilder.append(" - invoked with params:").append("(").append(InterceptorUtils.parseParams(params)).append(")");
		return stringBuilder.toString();
	}
	
	public static String getMessageAfterInvokation(InvocationContext inv, Object result) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(getMethodFullName(inv));
		stringBuilder.append(" - returned:").append(InterceptorUtils.parseResult(result));
		return stringBuilder.toString();
	}	
	
	public static String parseParams(Object[] params) {
		if (params == null || params.length == 0) {
			return "";
		}
		String str = "";
		//TODO what if params will have size quite wignificatn or will have list with big size
		str = Arrays.toString(params).replace("[", "").replace("]", "");
		return str;
	}

	@SuppressWarnings("unchecked")
	public static String parseResult(Object result) {
		if (result == null) {
			return "null";
		}
		if (result instanceof Collection) {
			StringBuilder stringBuilder = new StringBuilder();
			Collection<Object> col = (Collection<Object>) result;
			int size = col.size();
			stringBuilder.append(result.getClass().getName());
			stringBuilder.append("{");
			stringBuilder.append("size:").append(size);
			stringBuilder.append("}");
			return stringBuilder.toString();
		} else {
			return result.toString();
		}
	}
	
	public static String getMethodFullName(InvocationContext inv) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(inv.getTarget().getClass().getName()).append(".").append(inv.getMethod().getName()).append("()");
		return stringBuilder.toString();
	}
}
